package com.prodog.listener;

import com.prodog.command.core.GameCommandHandler;
import com.prodog.command.entity.CommandResult;
import com.prodog.command.entity.GameCommand;
import com.prodog.message.sender.SimBotMessageSender;
import lombok.RequiredArgsConstructor;
import love.forte.simboot.annotation.Listener;
import love.forte.simbot.event.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
@RequiredArgsConstructor
public class SimBotMessageListener {
    private final GameCommandHandler handler;
    private final SimBotMessageSender sender;
    private AtomicInteger gcFlag = new AtomicInteger(0);


    @Listener
    public void onFriendMsgEvent(FriendMessageEvent event) {
        GameCommand command = new GameCommand() {{
            setFromQQ(String.valueOf(event.getUser().getId()));
            setType(1);
            setCommand(event.getMessageContent().getPlainText());
        }};
        CommandResult res = handler.handle(command);
        if (res != null && Strings.isNotEmpty(String.valueOf(res.getResult()))) {
            sender.sendToSelf(event.getFriend().getId().toString(), String.valueOf(res.getResult()).trim());
        }
        if (gcFlag.incrementAndGet() % 20 == 0) {
            System.gc();
        }
    }

    @Listener
    public void onGroupMsgEvent(GroupMessageEvent event) {
        GameCommand command = new GameCommand() {{
            setFromQQ(String.valueOf(event.getAuthor().getId()));
            setType(2);
            setCommand(event.getMessageContent().getPlainText());
        }};
        CommandResult res = handler.handle(command);
        if (res != null && Strings.isNotEmpty(String.valueOf(res.getResult()))) {
            sender.sendToGroup(event.getGroup().getId().toString(), String.valueOf(res.getResult()).trim());

        }
        if (gcFlag.incrementAndGet() % 20 == 0) {
            System.gc();
        }
    }

    @Listener
    public void onFriendAddEvent(FriendAddRequestEvent event) {
        event.acceptAsync();
    }

    @Listener
    public void onGroupAddEvent(GroupJoinRequestEvent event) {
        event.acceptAsync();
    }
}
